<template>
  <view class="addressLimit">
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <loading :showLoaded.sync="showLoaded"></loading>
    <view class="goodsInfo">
      <view class="gImg">
        <image mode="widthFix" :src="basicInfo.image">
        </image>
      </view>
      <view class="rightText">
        <view class="gName">
          {{basicInfo.itemName}}
        </view>
        <view class="bottomBlock">
          <view class="price">
            <label>¥</label>{{filterChecked.moneyFormat(basicInfo.price/1, 2)}}
          </view>
          <view class="tool" @click="changeGoods()">
            切换商品<label class="macallan-icon mcl-youjiantou"></label>
          </view>
        </view>
      </view>
    </view>
    <view class="area">
      <view class="describe">
        限发地区将根据实际情况不定期更新，以下仅为参考。如您所在的地区无法下单，可咨询客服了解最新限行讯息：
      </view>
      <view class="selectBox">
        <view class="selectArea" @click="openAreaPicker">
          <!-- 默认状态 -->
          <view class="defaultText" v-if='!defaultAddress.receiverState '>请选择商品寄送地区</view>
          <!-- 有地址状态 -->
          <view class="addressText" v-else>
            <label v-if="defaultAddress.receiverState">{{defaultAddress.receiverState}} </label>
            <label v-if="defaultAddress.receiverCity">{{defaultAddress.receiverCity}}</label>
            <label v-if="defaultAddress.receiverDistrict">{{defaultAddress.receiverDistrict}}</label>
            <label v-if="defaultAddress.receiverTown">{{defaultAddress.receiverTown}}</label>
          </view>
          <label class="macallan-icon mcl-youjiantou"></label>
        </view>
        <view class="tipText">
          温馨提示：请您不要将未成年人作为订单的收件人，或让未成年人接触所购酒类商品。
        </view>
      </view>
      <view class="resultTitle">
        因临时情况或其他不可抗力原因，以下地区暂时无法发货
      </view>
      <view class="resultList" :class="[isIpx ? 'fix-iphonex-button' : '']" >
        <!-- 不在疫情限行地区文案 -->
        <view class="noLimit" v-if="restrictAddress.length<1">
          该地址目前不在限发地区
        </view>
        <view class="rItem" v-for="(item,index) in restrictAddress" :key='index'>
          <label>{{item}}</label>
        </view>
      </view>
      <view class="bottomBox" :class="[isIpx ? 'fix-iphonex-button' : '']"  @click="openAreaPicker">
        <view class="bottomBtn">{{btnText}}</view>
      </view>
    </view>

    <!-- 不属于疫情地区弹层 -->
    <vive class="topView" @touchmove.stop.prevent catchtouchmove="true" v-if="showDialog">
      <view class="center">
        <view class="macallan-icon mcl-guanbi1" @click="closeShowDialog('关闭')"></view>
        <view class="title">
          {{dialogTitle}}
        </view>
        <view class="text">
          {{dialogContent}}
        </view>
        <view class="btn" @click="closeShowDialog('确认')">
          确认
        </view>
      </view>
    </vive>
    <!-- 商品限行地区查询弹层 -->
    <view class="topView_B" v-if='showList' @touchmove.stop.prevent catchtouchmove="true">
      <view class="content">
        <view class="macallan-icon mcl-guanbi1" @click="showList=false"></view>
        <view class="title">
          商品限发地区查询
        </view>
        <scroll-view class="goodsQueryList" scroll-y="true">
          <view class="gItem" v-for="(item,index) in productList" :key="index">
            <view class="gImg">
              <image mode="widthFix" :src="item.majorUrl">
              </image>
            </view>
            <view class="rText">
              <view class="gName">{{item.itemName}}</view>
              <view class="bView">
                <view class="price">
                  <label>¥</label>{{filterChecked.moneyFormat(item.price/1, 2)}}
                </view>
                <view class="rBtn" @click="doSearch(item)">
                  查询商品
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <areaPicker ref='areaRef' @areaArray='setAddress'  @setSelectCode='setSelectCode'></areaPicker>
  </view>
</template>
<script module="filterChecked" lang="wxs" src="../../utils/filter.wxs"></script>
<script>
  import api from '@/api/api';
  import tip from '@/utils/tip';
  import NavBar from '../../components/common/navbar';
  import Loading from '../../components/common/loading';
  import {
    SYSTEM_INFO,
    USER_INFO,
    CUSTOMER_INFO,
    MERCHANT_INFO,
  } from '@/utils/constant';
  import areaPicker from './newAreaPicker.vue'
  export default {
    config: {
      navigationStyle: 'custom',
      navigationBarTitleText: ''
    },
    components: {
      navBar: NavBar,
      Loading: Loading,
      areaPicker: areaPicker
    },
    data() {
      return {
        navbarData: {
          showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
          navbarTitle: '限发地区说明',
          hideSearch: true,
          hideHome: false,
        },
        isShowCustomNavBar: true,
        isIpx: false,
        defaultAddress: {
          receiverState: '',
          receiverCity: '',
          receiverDistrict: '',
          receiverTown: ''
        },
        showList: false,
        productList: [],
        basicInfo: {},
        itemId: '',
        valueId: '',
        showLoaded: true,
        restrictAddress: [],
        showDialog: false,
        dialogTitle: '',
        dialogContent: '',
        btnText: '选择商品寄送地区',
        defaultSelectCode: []
      };
    },
    mounted() {

    },
    onLoad: async function(option) {
      let systemInfo = uni.getSystemInfoSync();
      let isIpx = systemInfo.model.indexOf('iPhone X') !== -1 || systemInfo.model.indexOf('iPhone1') !== -1 ||
        systemInfo.model.indexOf('unknown<iPhone13') !== -1 || systemInfo.model.indexOf('iPhone 12/13') !== -1;
      this.isIpx = isIpx;
      this.getGoodList()
      this.itemId = option.id
      await this.getGoodInfo()
    },
    onShow: async function() {},
    computed: {

    },
    methods: {
      //用户默认收货地址
      getUserAddress: async function() {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO)
        let jwt = uni.getStorageSync(CUSTOMER_INFO).jwt;
        const json = await api.getUserAddress({
          header: {
            jwt: jwt
          },

        });
        if (json.code === 1000) {
          let addressListArray = json.data.content;
          if (addressListArray.length > 0) {
            let hasDefault = addressListArray.filter(item => {
              return item.isDefault == 1
            })
            if (hasDefault.length > 0) {
              this.defaultAddress = hasDefault[0]
              let provinceCode, cityCode, areaCode, townCode;
              provinceCode = this.defaultAddress.areaCode.slice(0, 2) + '0000000'
              cityCode = this.defaultAddress.receiverCity ? this.defaultAddress.areaCode.slice(0, 4) + '00000' : null
              areaCode = this.defaultAddress.receiverDistrict ? this.defaultAddress.areaCode.slice(0, 6) + '000' : null
              townCode = this.defaultAddress.receiverTown ? this.defaultAddress.areaCode : null
              this.defaultSelectCode.push(provinceCode, cityCode, areaCode, townCode)
              this.defaultSelectCode = this.defaultSelectCode.filter((item) => (item))
              if(!this.defaultAddress.areaCode){
                this.defaultSelectCode= []
              }
              this.$refs.areaRef.setSelectCode(this.defaultSelectCode)
              this.btnText = '切换商品寄送地区'
            }
          }
          this.pdpRestrictAddress(true)
          this.showLoaded = false
        } else {
          this.showLoaded = false
        }
      },
      changeGoods() {
        this.showList = true
      },
      openAreaPicker() {
          this.$refs.areaRef.openAddressPicker()
      },
      setAddress(province, city, area, town) {
        this.$nextTick(() => {
          this.defaultAddress.receiverState = province.areaId ? province.areaName : ''
          this.defaultAddress.receiverCity = city.areaId ? city.areaName : ''
          this.defaultAddress.receiverDistrict = area.areaId ? area.areaName : ''
          this.defaultAddress.receiverTown = town.areaId ? town.areaName : ''
          this.pdpRestrictAddress()
          this.btnText = '切换商品寄送地区'
        })
      },
      async getGoodList() {
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
        let classId

        if (api.environment == 'formal') {
          classId = 18054
        } else if (api.environment == 'trial') {
          classId = 8018
        }
        const json = await api.getGoodsListNew({
          query: {
            page_no: 1,
            page_size: 100,
            merchant_id: merchantInfo.cloudMerchantId,
            store_id: merchantInfo.cloudMerchantStoreId,
            after_page: '',
            class_id: classId
          }
        });
        if (json.code === 1000) {
          this.productList = json.data.content
        }
      },
      async getGoodInfo() {
        let merchantInfo = uni.getStorageSync('merchantInfo');
        const json = await api.goodsDetail({
            query: {
              merchant_id: merchantInfo.cloudMerchantId,
              store_id: merchantInfo.cloudMerchantStoreId
            }
          },
          this.itemId
        );
        if (json.code === 1000) {
          this.basicInfo.itemName = json.data.itemName
          this.basicInfo.image = json.data.skus[0].skuImageUrl
          this.basicInfo.price = json.data.skus[0].price
          this.valueId = json.data.frontProperties[0].valueId
		      this.trackLimitAddr(json.data);
          this.getUserAddress()
        }
      },

		trackChangeProduct(item){
			let that = this;
			let clTrackPrams = {
				'c_product_name': item.itemName,
				'c_product_brand': '',
				'c_product_price': item.price,
				'c_product_year': '',
				'c_product_series': '',
				'c_product_scenarios': '',
				'c_product_taste': '',
				'c_product_alcoholconcentration': '',
				'c_product_volume': item.valueName,
			};
			getApp().commonClTrack('c_ebmp_product_restricted_area_change_product', clTrackPrams)
		},
		trackLimitAddr(detail){
			let that = this;
			let frontCustomParameters = JSON.parse(detail.frontProperties[0].frontCustomParameters);
			let clTrackPrams = {
				'c_product_name': detail.itemName,
				'c_product_brand': frontCustomParameters.brand,
				'c_product_price': detail.skus[0].price,
				'c_product_year': '',
				'c_product_series': frontCustomParameters.series,
				'c_product_scenarios': '',
				'c_product_taste': '',
				'c_product_alcoholconcentration': frontCustomParameters.degrees,
				'c_product_volume': detail.frontProperties[0].valueName,
			};
			getApp().commonClTrack('c_ebmp_product_click_restricted_area', clTrackPrams)
		},
      doSearch(item) {
        this.showList = false
        this.basicInfo.itemName = item.itemName
        this.basicInfo.image = item.majorUrl
        this.basicInfo.price = item.price
        this.itemId = item.itemId
        this.valueId = item.valueId
		this.trackChangeProduct(item);
        if (this.defaultAddress) {
          this.pdpRestrictAddress()
        }
      },
      async pdpRestrictAddress(isDefault = false) {
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
        let json = await api.pdpRestrictAddress({
          method: 'POST',
          query: {
            city: this.defaultAddress.receiverCity,
            district: this.defaultAddress.receiverDistrict,
            itemId: this.itemId,
            merchantId: merchantInfo.cloudMerchantId,
            state: this.defaultAddress.receiverState,
            storeId: merchantInfo.cloudMerchantStoreId,
            valueId: this.valueId,
            town: this.defaultAddress.receiverTown
          }
        })
        if (json.code === 1000) {
          this.restrictAddress = json.data
		   let clTrackPrams = {};
		   let eventName = '';
		   let hierarchy = '';
		   if(!!this.defaultAddress.receiverTown){
			   hierarchy = '街道';
		   }else if(!!this.defaultAddress.receiverDistrict && !this.defaultAddress.receiverTown){
			   hierarchy = '区';
		   }else if(!!this.defaultAddress.receiverCity && !this.defaultAddress.receiverDistrict){
			   hierarchy = '市';
		   }else if(!!this.defaultAddress.receiverState && !this.defaultAddress.receiverCity){
			   hierarchy = '省';
		   }
		  if(isDefault){
				eventName = 'c_ebmp_product_restricted_area_default_answer';
				clTrackPrams = {
			  	'c_default_address_province': this.defaultAddress.receiverState,
			  	'c_default_address_city': this.defaultAddress.receiverCity,
			  	'c_default_address_county': this.defaultAddress.receiverDistrict,
			  	'c_default_address_area': this.defaultAddress.receiverTown,
			  	'c_address_hierarchy': hierarchy,
			  	'c_address_answer': '',
				};
		  }else{
			  eventName = 'c_ebmp_product_restricted_area_answer';
			  clTrackPrams = {
			  	'c_address_province': this.defaultAddress.receiverState,
			  	'c_address_city': this.defaultAddress.receiverCity,
			  	'c_address_county': this.defaultAddress.receiverDistrict,
			  	'c_address_area': this.defaultAddress.receiverTown,
			  	'c_address_hierarchy': hierarchy,
			  	'c_address_answer': '',
			  	};
		  }

          if (this.defaultAddress.receiverState) {
            if (this.restrictAddress.length > 0) {
              this.dialogTitle = '当前地址属于限发地区';
              this.dialogContent = '查询到您当前的收货地址属于限发地区，具体可参考以下列表。为您造成的不便，敬请谅解！'
			  let length = this.restrictAddress.length;
			  clTrackPrams.c_address_answer = length > 1 ? '多个地址不可发货' : '该地址不可发货';
			} else {
              this.dialogTitle = '当前地址暂不属于限发地区'
              this.dialogContent = '查询到您当前的收货地址暂时不在限发地区。'
			  clTrackPrams.c_address_answer = '可发货';
            }
            this.showDialog = true
            this.$commonSensors.popupEvent('PopupExposure', {'popup_type' : '限行查询', 'popup_name': '限行地址提示弹窗'})
			getApp().commonClTrack(eventName, clTrackPrams)
          }
        }
      },
      closeShowDialog(type) {
        this.showDialog = false
        this.$commonSensors.popupEvent('PopupClick', {'popup_type' : '限行查询', 'popup_name': '限行地址提示弹窗', 'button_name': type})
      }
    }
  };
</script>
<style lang="less">
  page {
    background: #F5F5F5;
    height: 100%;
  }
  .addressLimit{
    height: 100%;
    overflow: hidden;
  }
  .goodsInfo {
    display: flex;
    padding: 40rpx 30rpx;
    background: #fff;
    border-top: 2rpx solid rgba(184, 184, 184, .3);

    .gImg {
      image {
        width: 180rpx;
        display: block;
      }
    }

    .rightText {
      margin-left: 30rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      width: 100%;

      .gName {
        font-size: 26rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        color: #030303;
        line-height: 36rpx;
        font-weight: bold;
      }

      .bottomBlock {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .price {
          font-size: 34rpx;
          font-family: PingFangSC-Regular, PingFang SC;
          color: #000;
          font-weight: bold;

          label {
            font-size: 28rpx;
          }
        }

        .tool {
          line-height: 1;
          font-size: 24rpx;

          .mcl-youjiantou {

            font-size: 24rpx;
            margin-left: 25rpx;
            color: #000;
          }
        }
      }
    }
  }

  .area {
    padding: 40rpx 40rpx 0;
    background: #F5F5F5;
    display: flex;
    flex-direction: column;
    height: calc(100% - 240rpx);
    .describe {
      font-size: 22rpx;
      padding: 0 10rpx;
      margin-bottom: 30rpx;
      font-family: SHS-Regular;
      color: #343434;
    }

    .selectBox {
      background-color: #fff;
      border: 2rpx solid #D5D5D5;
      padding: 40rpx 30rpx;
      margin-bottom: 20rpx;

      .selectArea {
        border: 2rpx solid #979797;
        background-color: #F5F5F5;
        padding: 38rpx 24rpx;
        margin-bottom: 30rpx;
        line-height: 1;
        display: flex;
        justify-content: space-between;

        .defaultText {
          font-size: 24rpx;
          font-family: "SHS-Regular";
        }

        .addressText label {
          margin-right: 12rpx;
          font-size: 24rpx;
          font-family: "SHS-Regular";
        }

        .mcl-youjiantou {
          font-size: 24rpx;
          display: flex;
          align-items: center;
        }
      }

      .tipText {
        color: #AEAEAE;
        font-size: 18rpx;
        line-height: 26rpx;
        font-family: "SHS-Regular";
      }
    }

    .resultTitle {
      margin: 0 0 20rpx 10rpx;
      font-size: 24rpx;
      font-family: PingFangSC-Regular, PingFang SC;
    }

    .resultList {
      border: 2rpx solid #D5D5D5;
      background-color: #fff;
      padding: 50rpx;
      height: calc(100% - 690rpx);
      overflow-y: auto;
      &.fix-iphonex-button{
        height: calc(100% - 760rpx);
      }
      .rItem {
        margin-bottom: 60rpx;
        font-size: 26rpx;
        color: #030303;
        font-family: PingFangSC-Regular, PingFang SC;

        &:last-child {
          margin-bottom: 0;
        }

        label {
          margin-right: 12rpx;
        }
      }

      .noLimit {
        font-family: PingFangSC-Regular, PingFang SC;
        color: #AEAEAE;
        text-align: center;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }

  .bottomBox {
    position: fixed;
    width: 100%;
    bottom: 0rpx;
    background: #fff;
    left: 0;
    right: 0;

    &.fix-iphonex-button {
      padding-bottom: 40rpx;
    }
  }

  .bottomBtn {
    background-color: #010101;
    font-size: 32rpx;
    text-align: center;
    color: #fff;
    padding: 32rpx 0;
    font-family: PingFangSC-Regular, PingFang SC;
  }

  .topView {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, .5);
    display: flex;
    justify-content: center;
    align-items: center;

    .center {
      background-color: #fff;
      width: 520rpx;
      padding: 46rpx 64rpx 52rpx;
      position: relative;

      .mcl-guanbi1 {
        position: absolute;
        right: 0;
        top: 0;
        font-size: 22rpx;
        padding: 22rpx;
      }

      .title {
        font-size: 28rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        color: #000;
        margin-bottom: 32rpx;
        font-weight: bold;
        text-align: center;
      }

      .text {
        font-size: 26rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        margin-bottom: 56rpx;
        text-align: justify;
      }

      .btn {
        width: 197rpx;
        height: 67rpx;
        background: #000;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 26rpx;
        font-family: PingFangSC-Regular, PingFang SC;
        letter-spacing: 2rpx;
        margin: auto;
      }
    }
  }

  /* 底部弹层 */
  .topView_B {
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 100vh;
    background-color: rgba(0, 0, 0, .7);
    display: flex;
    justify-content: center;
    align-items: flex-end;

    .content {
      background-color: #fff;
      width: 100%;
      position: relative;

      .mcl-guanbi1 {
        position: absolute;
        right: 0;
        top: 0;
        font-size: 22rpx;
        padding: 38rpx 30rpx;
      }

      .title {
        font-size: 34rpx;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: bold;
        margin: 32rpx 0 30rpx;
        text-align: center;
        line-height: 1;
      }

      .goodsQueryList {
        overflow-y: auto;
        border-top: 2rpx solid #EEE;
        height: 65vh;
        /* 1120rpx */
        margin-bottom: 40rpx;

        .gItem {
          display: flex;
          padding: 30rpx;
          border-bottom: 2rpx solid #EEE;

          .gImg image {
            width: 160rpx;
            display: block;
          }

          .rText {
            margin-left: 30rpx;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            flex:1;

            .gName {
              font-size: 24rpx;
              font-family: PingFangSC-Regular, PingFang SC;
              color: #030303;
              line-height: 34rpx;
            }

            .bView {
              display: flex;
              justify-content: space-between;
              align-items: center;

              .price {
                font-size: 30rpx;

                label {
                  font-size: 24rpx;
                }
              }

              .rBtn {
                width: 160rpx;
                height: 46rpx;
                background-color: #333;
                color: #fff;
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 24rpx;
                font-family: PingFangSC-Regular, PingFang SC;
              }
            }
          }
        }
      }
    }
  }
</style>
